<template>
  <basic-container>
    <div class="system-config-center">
      <!-- 页面标题和操作按钮 -->
      <div class="page-header">
        <h1 class="page-title">系统配置中心</h1>
        <div class="action-buttons">
          <el-button type="primary" class="save-btn" @click="handleSave">保存</el-button>
          <el-button class="clear-btn" @click="handleClear">清除修改</el-button>
        </div>
      </div>

      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="0">
        <!-- 信息费 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="section-title">
              <span>信息费</span>
            </div>
          </template>
          <el-form class="config-form" label-width="0">
            <el-form-item class="config-row" prop="informationFee">
              <span class="config-label">非营运车主单次行程完成收取车主实际需收总额的</span>
              <el-input v-model="formData.informationFee" type="number" class="config-input" placeholder="请输入百分比" />
              <span class="config-unit">% 作为信息费 (0≤x≤100, x需为整数)</span>
            </el-form-item>

          </el-form>
        </el-card>

        <!-- 推广费 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="section-title">
              <span>推广费</span>
            </div>
          </template>
          <el-form class="config-form" label-width="0">
            <el-form-item class="config-row" prop="passengerPromotionFee">
              <span class="config-label">乘客行程:C推广成员作为乘客行程完成,车主支付信息费后B推广人可获得乘客行程信息费</span>
              <el-input v-model="formData.passengerPromotionFee" type="number" class="config-input"
                placeholder="请输入百分比" />
              <span class="config-unit">% 作为推广费 (0≤x≤100, x需为整数)</span>
            </el-form-item>
            <el-form-item class="config-row" prop="ownerPromotionFee">
              <span class="config-label">车主行程:C推广成员作为车主行程完成,支付信息费后B推广人可获得车主行程信息费</span>
              <el-input v-model="formData.ownerPromotionFee" type="number" class="config-input" placeholder="请输入百分比" />
              <span class="config-unit">% 作为推广费 (0≤x≤100, x需为整数)</span>
            </el-form-item>
            <el-form-item class="config-row" prop="passengerIndirectPromotionFee">
              <span class="config-label">乘客行程:C推广成员作为乘客行程完成,车主支付信息费后A推广人可获得乘客行程信息费</span>
              <el-input v-model="formData.passengerIndirectPromotionFee" type="number" class="config-input"
                placeholder="请输入百分比" />
              <span class="config-unit">% (0≤x≤100, x需为整数)</span>
            </el-form-item>
            <el-form-item class="config-row" prop="ownerIndirectPromotionFee">
              <span class="config-label">车主行程:C推广成员作为车主行程完成,支付信息费后A推广人可获得车主行程信息费</span>
              <el-input v-model="formData.ownerIndirectPromotionFee" type="number" class="config-input"
                placeholder="请输入百分比" />
              <span class="config-unit">% (0≤x≤100, x需为整数)</span>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 有责退订 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="section-title">
              <span>有责退订</span>
            </div>
          </template>
          <el-form class="config-form" label-width="0">
            <el-form-item class="config-row" prop="cancelTimeLimit">
              <span class="config-label">乘客在出发时间前</span>
              <el-input v-model="formData.cancelTimeLimit" type="number" class="config-input" placeholder="请输入时间" />
              <span class="config-unit">分钟内退订选择乘客原因,扣除乘客</span>
              <el-input v-model="formData.passengerDeductPoints" type="number" class="config-input"
                placeholder="请输入积分" />
              <span class="config-unit">分诚信值选择车主原因,扣除车主</span>
              <el-input v-model="formData.ownerDeductPoints" type="number" class="config-input" placeholder="请输入积分" />
              <span class="config-unit">分诚信值</span>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 投诉评价 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="section-title">
              <span>投诉评价</span>
            </div>
          </template>
          <el-form class="config-form" label-width="0">
            <el-form-item class="config-row" prop="complaintTimeLimit">
              <span class="config-label">乘客/车主在行程完成</span>
              <el-input v-model="formData.complaintTimeLimit" type="number" class="config-input" placeholder="请输入时间" />
              <span class="config-unit">小时内可投诉</span>
            </el-form-item>
            <el-form-item class="config-row" prop="reviewTimeLimit">
              <span class="config-label">乘客在行程完成</span>
              <el-input v-model="formData.reviewTimeLimit" type="number" class="config-input" placeholder="请输入时间" />
              <span class="config-unit">小时内可评价</span>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 客服电话 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="section-title">
              <span>客服电话</span>
            </div>
          </template>
          <el-form class="config-form" label-width="0">
            <el-form-item class="config-row" prop="servicePhone">
              <span class="config-label">对外客服电话</span>
              <el-input v-model="formData.servicePhone" class="config-input" placeholder="请输入客服电话"
                style="width: 300px !important;" />
            </el-form-item>
          </el-form>
        </el-card>
      </el-form>
    </div>
  </basic-container>
</template>

<script>
import { getConfigList, updateConfig } from './api/config'

export default {
  name: 'SystemConfigCenter',
  data () {
    return {
      formRef: null,
      formData: {
        // 信息费
        informationFee: '',
        passengerIndirectPromotionFee: '',
        ownerIndirectPromotionFee: '',

        // 推广费
        passengerPromotionFee: '',
        ownerPromotionFee: '',

        // 有责退订
        cancelTimeLimit: '',
        passengerDeductPoints: '',
        ownerDeductPoints: '',

        // 投诉评价
        complaintTimeLimit: '',
        reviewTimeLimit: '',

        // 客服电话
        servicePhone: '',
      },
      formRules: {
        informationFee: [
          { required: true, message: '请输入信息费百分比', trigger: 'blur' },
          { type: 'number', min: 0, max: 100, message: '信息费百分比必须在0-100之间', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== '' && !Number.isInteger(Number(value))) {
                callback(new Error('信息费百分比必须为整数'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        passengerIndirectPromotionFee: [
          { required: true, message: '请输入间接推广人乘客信息费百分比', trigger: 'blur' },
          { type: 'number', min: 0, max: 100, message: '间接推广费百分比必须在0-100之间', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== '' && !Number.isInteger(Number(value))) {
                callback(new Error('间接推广费百分比必须为整数'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        ownerIndirectPromotionFee: [
          { required: true, message: '请输入间接推广人车主信息费百分比', trigger: 'blur' },
          { type: 'number', min: 0, max: 100, message: '间接推广费百分比必须在0-100之间', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== '' && !Number.isInteger(Number(value))) {
                callback(new Error('间接推广费百分比必须为整数'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        passengerPromotionFee: [
          { required: true, message: '请输入乘客推广费百分比', trigger: 'blur' },
          { type: 'number', min: 0, max: 100, message: '推广费百分比必须在0-100之间', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== '' && !Number.isInteger(Number(value))) {
                callback(new Error('推广费百分比必须为整数'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        ownerPromotionFee: [
          { required: true, message: '请输入车主推广费百分比', trigger: 'blur' },
          { type: 'number', min: 0, max: 100, message: '推广费百分比必须在0-100之间', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== '' && !Number.isInteger(Number(value))) {
                callback(new Error('推广费百分比必须为整数'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        cancelTimeLimit: [
          { required: true, message: '请输入退订时间限制', trigger: 'blur' },
          { type: 'number', min: 1, message: '时间必须大于0', trigger: 'blur' }
        ],
        passengerDeductPoints: [
          { required: true, message: '请输入乘客扣除积分', trigger: 'blur' },
          { type: 'number', min: 0, message: '积分不能为负数', trigger: 'blur' }
        ],
        ownerDeductPoints: [
          { required: true, message: '请输入车主扣除积分', trigger: 'blur' },
          { type: 'number', min: 0, message: '积分不能为负数', trigger: 'blur' }
        ],
        complaintTimeLimit: [
          { required: true, message: '请输入投诉时间限制', trigger: 'blur' },
          { type: 'number', min: 1, message: '时间必须大于0', trigger: 'blur' }
        ],
        reviewTimeLimit: [
          { required: true, message: '请输入评价时间限制', trigger: 'blur' },
          { type: 'number', min: 1, message: '时间必须大于0', trigger: 'blur' }
        ],
        servicePhone: [
          { required: true, message: '请输入客服电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      configData: null
    }
  },
  methods: {
    // 验证数据格式
    validateFormData () {
      const data = this.formData

      // 检查必填字段
      const requiredFields = [
        'informationFee', 'passengerIndirectPromotionFee', 'ownerIndirectPromotionFee',
        'passengerPromotionFee', 'ownerPromotionFee',
        'cancelTimeLimit', 'passengerDeductPoints', 'ownerDeductPoints',
        'complaintTimeLimit', 'reviewTimeLimit', 'servicePhone'
      ]

      for (const field of requiredFields) {
        if (data[field] === '' || data[field] === null || data[field] === undefined) {
          this.$message.error(`请填写${this.getFieldLabel(field)}`)
          return false
        }
      }

      // 检查数值范围
      if (data.informationFee < 0 || data.informationFee > 100) {
        this.$message.error('信息费百分比必须在0-100之间')
        return false
      }

      if (data.passengerIndirectPromotionFee < 0 || data.passengerIndirectPromotionFee > 100) {
        this.$message.error('间接推广人乘客信息费百分比必须在0-100之间')
        return false
      }

      if (data.ownerIndirectPromotionFee < 0 || data.ownerIndirectPromotionFee > 100) {
        this.$message.error('间接推广人车主信息费百分比必须在0-100之间')
        return false
      }

      if (data.passengerPromotionFee < 0 || data.passengerPromotionFee > 100) {
        this.$message.error('乘客推广费百分比必须在0-100之间')
        return false
      }

      if (data.ownerPromotionFee < 0 || data.ownerPromotionFee > 100) {
        this.$message.error('车主推广费百分比必须在0-100之间')
        return false
      }

      return true
    },

    // 获取字段标签
    getFieldLabel (field) {
      const labels = {
        informationFee: '信息费百分比',
        passengerIndirectPromotionFee: '间接推广人乘客信息费百分比',
        ownerIndirectPromotionFee: '间接推广人车主信息费百分比',
        passengerPromotionFee: '乘客推广费百分比',
        ownerPromotionFee: '车主推广费百分比',
        cancelTimeLimit: '退订时间限制',
        passengerDeductPoints: '乘客扣除积分',
        ownerDeductPoints: '车主扣除积分',
        complaintTimeLimit: '投诉时间限制',
        reviewTimeLimit: '评价时间限制',
        servicePhone: '客服电话'
      }
      return labels[field] || field
    },

    // 根据code获取配置项id
    getConfigIdByCode (code) {
      if (!this.configData || !Array.isArray(this.configData)) return null
      const configItem = this.configData.find(item => item.code === code)
      return configItem ? configItem.id : null
    },

    // 回填配置数据
    fillConfigData () {
      if (!this.configData || !Array.isArray(this.configData)) return

      // 创建配置映射
      const configMap = {}
      this.configData.forEach(item => {
        configMap[item.code] = item.value
      })

      // 信息费 - 转换为百分比显示
      this.formData.informationFee = configMap.service_fee ? Math.round(Number(configMap.service_fee) * 100) : ''
      this.formData.passengerIndirectPromotionFee = configMap.promotor_passenger_indirect_service_fee ? Math.round(Number(configMap.promotor_passenger_indirect_service_fee) * 100) : ''
      this.formData.ownerIndirectPromotionFee = configMap.promotor_car_owner_indirect_service_fee ? Math.round(Number(configMap.promotor_car_owner_indirect_service_fee) * 100) : ''

      // 推广费 - 转换为百分比显示
      this.formData.passengerPromotionFee = configMap.promotor_passenger_service_fee ? Math.round(Number(configMap.promotor_passenger_service_fee) * 100) : ''
      this.formData.ownerPromotionFee = configMap.promotor_car_owner_service_fee ? Math.round(Number(configMap.promotor_car_owner_service_fee) * 100) : ''

      // 有责退订
      this.formData.cancelTimeLimit = configMap.unsub_time_limit || ''
      this.formData.passengerDeductPoints = configMap.passenger_reason_unsub_deduction || ''
      this.formData.ownerDeductPoints = configMap.car_owner_reason_unsub_deduction || ''

      // 投诉评价
      this.formData.complaintTimeLimit = configMap.travel_complaints_hours || ''
      this.formData.reviewTimeLimit = configMap.travel_evaluate_hours || ''

      // 客服电话
      this.formData.servicePhone = configMap.service_tel || ''
    },

    // 保存方法
    async handleSave () {
      try {
        // 表单验证
        const valid = await this.$refs.formRef.validate()
        if (!valid) return

        // 自定义数据验证
        if (!this.validateFormData()) return

        // 显示确认对话框
        this.$confirm('新设置保存后立即生效，确认保存吗？', '保存确认', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(async () => {
          // 构建提交数据 - 保持与接口获取的数据类型一致
          const submitData = {
            config: [
              {
                id: this.getConfigIdByCode('service_fee'),
                value: (Number(this.formData.informationFee) / 100).toString(),
              },
              {
                id: this.getConfigIdByCode('promotor_passenger_indirect_service_fee'),
                value: (Number(this.formData.passengerIndirectPromotionFee) / 100).toString(),
              },
              {
                id: this.getConfigIdByCode('promotor_car_owner_indirect_service_fee'),
                value: (Number(this.formData.ownerIndirectPromotionFee) / 100).toString(),
              },
              {
                id: this.getConfigIdByCode('promotor_passenger_service_fee'),
                value: (Number(this.formData.passengerPromotionFee) / 100).toString(),
              },
              {
                id: this.getConfigIdByCode('promotor_car_owner_service_fee'),
                value: (Number(this.formData.ownerPromotionFee) / 100).toString(),
              },
              {
                id: this.getConfigIdByCode('unsub_time_limit'),
                value: this.formData.cancelTimeLimit.toString(),
              },
              {
                id: this.getConfigIdByCode('passenger_reason_unsub_deduction'),
                value: this.formData.passengerDeductPoints.toString(),
              },
              {
                id: this.getConfigIdByCode('car_owner_reason_unsub_deduction'),
                value: this.formData.ownerDeductPoints.toString(),
              },
              {
                id: this.getConfigIdByCode('travel_complaints_hours'),
                value: this.formData.complaintTimeLimit.toString(),
              },
              {
                id: this.getConfigIdByCode('travel_evaluate_hours'),
                value: this.formData.reviewTimeLimit.toString(),
              },
              {
                id: this.getConfigIdByCode('service_tel'),
                value: this.formData.servicePhone,
              }
            ]
          }
          const res = await updateConfig(submitData)
          if (res.err === 0) {
            // 保存成功后重新获取最新数据
            const refreshRes = await getConfigList()
            if (refreshRes.err === 0) {
              this.configData = refreshRes.data
              this.fillConfigData() // 重新回填数据
            }
            this.$message.success('保存成功')
          } else {
            this.$message.error(res.msg || '保存失败')
          }
        }).catch(() => {
          // 用户取消保存，弹窗关闭，修改内容保留
        })
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败，请检查网络连接')
      }
    },

    // 取消修改方法
    handleClear () {
      this.$refs.formRef.resetFields()
      this.fillConfigData() // 重新回填数据，恢复到当前使用的配置
      this.$message.success('已清除修改')
    }
  },
  async created () {
    try {
      // 显示加载状态
      this.$loading({
        lock: true,
        text: '正在加载配置数据...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      // 加载配置数据
      const res = await getConfigList()
      if (res.err === 0) {
        this.configData = res.data
        this.fillConfigData() // 回填数据
        // this.$message.success('配置数据加载成功')
      } else {
        this.$message.error(res.msg || '获取配置失败')
      }
    } catch (error) {
      console.error('获取配置失败:', error)
      this.$message.error('获取配置失败，请检查网络连接')
    } finally {
      // 关闭加载状态
      this.$loading().close()
    }
  }
}
</script>

<style scoped lang="scss">
// 变量定义
$primary-color: #1890ff;
$primary-hover: #40a9ff;
$border-color: #d9d9d9;
$text-color: #333;
$text-secondary: #666;
$bg-color: #fff;
$bg-light: #fafafa;
$border-light: #f0f0f0;

// 混合器
@mixin flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

@mixin input-style {
  width: 140px !important;
  margin-right: 8px;

  :deep(.el-input__wrapper) {
    border-radius: 4px;
    border: 1px solid $border-color;
    box-shadow: none;
    height: 32px;

    &:hover {
      border-color: $primary-hover;
    }

    &.is-focus {
      border-color: $primary-color;
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
    }
  }

  :deep(.el-input__inner) {
    height: 30px;
    font-size: 14px;
    text-align: left;
  }
}

@mixin card-style {
  border: none;
  border-radius: 0;
  box-shadow: none;
  background: $bg-color;

  span {
    margin-right: 8px;
  }

  &:last-child {
    margin-bottom: 0;
  }

  :deep(.el-card__header) {
    padding: 16px;
    border-bottom: 1px solid $border-light;
    background: $bg-light;
    border-radius: 0;
    box-shadow: none;
    padding: 16px 24px !important;
  }

  :deep(.el-card__body) {
    padding: 24px;
  }
}

.system-config-center {
  padding: 20px;
}

.page-header {
  @include flex-center;
  justify-content: space-between;
  background-color: $bg-color;
  padding: 20px;
  margin-bottom: 24px;
  border-bottom: 1px solid $border-light;

  .page-title {
    font-size: 20px;
    font-weight: 600;
    color: $text-color;
    margin: 0;
  }

  .action-buttons {
    display: flex;
    gap: 12px;

    .save-btn {
      background: $primary-color;
      border-color: $primary-color;
      color: $bg-color;
      font-weight: 500;

      &:hover {
        background: $primary-hover;
        border-color: $primary-hover;
      }
    }

    .clear-btn {
      background: $bg-color;
      border-color: $border-color;
      color: $text-secondary;

      &:hover {
        border-color: $primary-color;
        color: $primary-color;
      }
    }
  }
}

.detail-card {
  @include card-style;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: $text-color;
}



.config-form {
  display: flex;
  flex-direction: column;

  .config-row {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .config-label {
      font-size: 14px;
      color: $text-color;
      white-space: nowrap;
    }

    .config-input {
      @include input-style;
    }

    .config-unit {
      font-size: 14px;
      color: $text-secondary;
      white-space: nowrap;
      margin-right: 8px;
    }
  }
}
</style>
